<template>
  <transition name="dialog-fade">
    <el-dialog class="dialog-component" :title="dialogTitle" :visible.sync="showDialog" width="500px">
      <el-form class="demo-form-inline" ref="formInfo" :model="formInfo" :rules="rules" label-width="120px">
        <el-form-item label="姓名：" prop="userName" required>
          <el-input v-model="formInfo.userName" autocomplete="off" placeholder="姓名必填"/>
        </el-form-item>
        <el-form-item label="手机号码：" prop="phoneNumber" required>
          <el-input v-model="formInfo.phoneNumber" autocomplete="off" placeholder="手机号码唯一、必填"/>
        </el-form-item>
        <el-form-item label="邮箱地址：" prop="email" required>
          <el-input v-model="formInfo.email" autocomplete="off" placeholder="邮箱地址唯一、必填"/>
        </el-form-item>
        <el-form-item v-if="formInfo.permission < $store.state.user.permission" label="权限类型：" prop="permission"
                      required>
          <el-select v-model="formInfo.permission" placeholder="请选择权限" default-last-option>
            <el-option label="超级管理员" :value="4" :disabled="$store.state.user.permission <= 3"/>
            <el-option label="管理员" :value="3" :disabled="$store.state.user.permission <= 3"/>
            <el-option label="领导用户（显示联系方式）" :value="2" :disabled="$store.state.user.permission <= 2"/>
            <el-option label="普通用户" :value="1" :disabled="$store.state.user.permission <= 2"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>初始密码为手机号后六位</div>
          <el-button v-show="formInfo.userId" size="mini"
                     :disabled="formInfo.permission >= $store.state.user.permission"
                     @click="adminResetPassword(formInfo)">恢复初始密码
          </el-button>
        </el-form-item>
        <el-form-item style="text-align: right;">
          <el-button type="primary" @click="submitForm('formInfo')">确定</el-button>
          <el-button @click="closeDialog(0)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </transition>
</template>

<script>
export default {
  name: "UserInformation",
  props: {
    dialogTitle: {type: String, default: "用户信息修改"},
    itemInfo: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    const checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[34578]\d{9}$$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        // Number.isInteger是es6验证数字是否为整数的方法,实际输入的数字总是识别成字符串
        // 所以在前面加了一个+实现隐式转换

        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    const checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    };
    return {
      showDialog: false,
      formInfo: JSON.parse(JSON.stringify(this.itemInfo)),
      rules: {
        phoneNumber: [{validator: checkPhone, trigger: "blur"}],
        email: [{validator: checkEmail, trigger: "blur"}],
      },
    };
  },
  methods: {
    adminResetPassword(user) {
      this.$http.post("api/user/adminResetPassword?userId=" + user.userId)
          .then(res => {
            if (200 === res.data.code) {
              this.$message({
                message: "初始化密码成功！",
                type: "success",
              });
            }
          })
    },
    submitForm(t) {
      var e = this,
          a = this;
      Object.assign(a.formInfo, {});
      a.$refs[t].validate(function (t) {
        if (!t) return !1;
        a.formInfo.userId
            ? e.$http
                .post("api/user/update", a.formInfo)
                .then(function (t) {
                  200 === t.data.code &&
                  (a.$message({
                    message: "修改成功！",
                    type: "success",
                  }),
                      a.closeDialog(1));
                })
            : e.$http
                .post("api/user/register", a.formInfo)
                .then(function (t) {
                  200 === t.data.code &&
                  (a.$message({
                    message: "注册成功！",
                    type: "success",
                  }),
                      a.closeDialog(1));
                });
      });
    },
    closeDialog(t) {
      this.$refs["formInfo"].resetFields()
      this.showDialog = false
      this.$emit("closeDialog", t)
    },
  },
}
</script>

<style scoped>
.dialog-fade-enter-active {
  -webkit-animation: dialog-fade-in 0.3s;
  animation: dialog-fade-in 0.3s;
}

.dialog-fade-leave-active {
  -webkit-animation: dialog-fade-out 0.3s;
  animation: dialog-fade-out 0.3s;
}
</style>